# -*- coding: utf-8 -*-

'''
@project : publicOpinionAnalysis_V2
@FileName: job_base
@Author  :linych 
@Time    :2020/5/9 16:24
@Desc  : 
'''

from Core import SYS_CODE
from Dao import t_job_dao



class JobFacotry(object):
    """
    任务类 ： id->conf

    关联 job, job_conf表

    def : select
    def : insert

    注：前置认定 job_id 和 conf_id 为 一对一
    通过job_id修改conf表

    """

    @classmethod
    def select_job(cls, jtype, job_id):
        conf_table_name = SYS_CODE.job_type_map.get(jtype)
        if conf_table_name is None:
            print('#FATAL: 任务[{}]映射不存在，{}'.format(jtype, SYS_CODE.job_type_map))
            return None

        res_list = t_job_dao.select_job_conf(conf_table_name, job_id)
        if res_list is not None and len(res_list)>0:
            return res_list[0]
        else:
            #若提取数据失败，commit后,重试一次
            t_job_dao.db_util.transaction_commit()
            res_list = t_job_dao.select_job_conf(conf_table_name, job_id)
            if res_list is not None and len(res_list) > 0:
                return res_list[0]
            print('#ERROR: 未获取到任务[{}-{}]'.format(jtype, job_id))
            return None


    @classmethod
    def insert_job(cls, jtype, status, **conf):
        conf_table_name = SYS_CODE.job_type_map.get(jtype)
        if conf_table_name is None:
            print('#FATAL: 任务[{}]映射存在问题，{}'.format(jtype, SYS_CODE.job_type_map))
            return False

        job_id,conf_id = t_job_dao.insert_job(jtype, status, conf_table_name, conf)

        return job_id,conf_id


    @classmethod
    def update_job(cls, job_id, status, jtype, **conf):
        t_job_dao.update_job(job_id, status)

        if conf is not None and len(conf):
            conf_table_name = SYS_CODE.job_type_map.get(jtype)
            if conf_table_name is None:
                print('#FATAL: 任务[{}]映射存在问题，{}'.format(jtype, SYS_CODE.job_type_map))
                return False

            t_job_dao.update_job_conf(job_id, conf_table_name, **conf)

        return True

    @classmethod
    def commit_data(cls):
        t_job_dao.db_util.transaction_commit()


if __name__ == '__main__':
    #job_fac = JobFacotry(SYS_CODE.job_type_map)

    pass
